7.4 技巧

让编译器检查,确保类型实现了指定接口。

type x int
  
func init() {              // 包初始化函数 
   var_fmt.Stringer=x(0) 
}

输出:

cannot use x(0) (type x)as type fmt.Stringer in assignment: 
   x does not implement fmt.Stringer(missing String method)

定义函数类型,让相同签名的函数自动实现某个接口。

type FuncString func()string
  
func(f FuncString)String()string{ 
   return f() 
} 
  
func main() { 
   var t fmt.Stringer=FuncString(func()string{   // 转换类型,使其实现Stringer接口 
       return"hello,world!" 
    }) 
  
   fmt.Println(t) 
}